package com.umeox.zikrringtest.auto_close.deviceManager

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.umeox.logger.UMLogger
import com.umeox.zikrringtest.auto_close.search.DeviceSearchManager
import com.umeox.base.CloseableCoroutineScope
import kotlinx.coroutines.*

private const val TAG = "DeviceListManager"

object DeviceListManager {
    /**
     * 最大支持设备
     */
    private const val MAX = 3

    /**
     * 设备携程空间
     */
    private val searchScope =
        com.umeox.base.CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    private var devices = mutableListOf<DeviceProxy>()
    private var observable = MutableLiveData(devices)

    val devicesObservable: LiveData<MutableList<DeviceProxy>> = observable

    fun addDevice(device: Device) {
        UMLogger.d(TAG,"添加设备 ${device.mac}")
        val deviceProxy = DeviceProxy(device)
        devices.add(deviceProxy)
        deviceProxy.startCloseTask()
    }

    fun startCloseTask() {
        UMLogger.d(TAG, "开始自动OTA任务")
        searchScope.launch(Dispatchers.IO) {
            for (i in 0 until MAX) {
                withContext(Dispatchers.Main) {
                    DeviceSearchManager.requestDeviceJoin()
                }
                delay(10 * 1000)
            }
        }
    }

    fun notifyStatusChange() {
        observable.postValue(devices)
    }
}